package com.dddpeter.app.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.dddpeter.app.common.Services;
import com.dddpeter.app.entity.User;
import com.dddpeter.app.object.BussinessService;

/** 
* @ClassName: LoginController 
* @Description: 登录页面控制程序
* @author Peter Lee
* @date 2014年8月11日 下午2:04:53 
*  
*/
@Controller
public class LoginController {
	private static final Logger LOG = Logger.getLogger(LoginController.class);
	@Resource(name = "loginService")
	BussinessService loginService;
	String emsg = "";
	
	/** 
	* @Title: Login 
	* @Description: 用户登录页面控制方法
	* @param username
	* @param password
	* @param session
	* @return ModelAndView
	* @throws 
	*/
	@RequestMapping(value = "/login.do")
	public ModelAndView Login(String username, String password,
			HttpSession session) {
		User user = new User();
		Map<String, Object> model = new HashMap<String, Object>();
		Map<Object, Object> paramMap = new HashMap<Object, Object>();
		if (username == null || password == null) {
			emsg = "请输入用户名和密码";
			model.put("emsg", emsg);
			return new ModelAndView("login", model);
		} 
		if (session.getAttribute("user") != null) {
			User user0 = (User) session.getAttribute("user");
			model.put("username", user0.getUserName());
			return new ModelAndView("home", model);
		}
		// 登录逻辑开始
		user.setUserName(username);
		user.setPassword(password);
		paramMap.put("user", user);
		loginService.service(Services.getLoginService(), paramMap);
		Map<Object,Object> resMap = loginService.output();
		if ((Boolean) resMap.get("login")) {
			user = (User) resMap.get("user");
			emsg = (String) resMap.get("emsg");
			session.setAttribute("user", user);
			session.setAttribute("username", username);
			model.put("username", username);
			LOG.info(emsg);
			model.put("emsg", emsg);
			return new ModelAndView("home", model);
		} else {
			model.put("emsg", "登录失败，请检查用户名或者密码");
		}

		LOG.info(emsg);
		return new ModelAndView("login", model);

	}

}
